package controller.v2;

import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.SortedMap;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alipay.api.response.AlipayTradeRefundResponse;

import model.LogEarnVO;
import model.LogOrder;
import model.MemberVO;
import model.OrderPayVO;
import model.OrderVO;
import service.v2.ConfigService;
import service.v2.MemberService;
import service.v2.MessageService;
import service.v2.OrderService;
import service.v2.PayService;
import service.v2.PushInterService;
import service.v2.PushService;
import service.v2.SplitService;
import service.v2.UorderPayService;
import service.v2.UorderService;
import util.ConfigUtil;
import util.PackageUtil;
import util.StringUtil;
import util.XMLUtil;

@Controller
@RequestMapping("/v2/orderPay")
public class UorderPayController {
     
	@Autowired
	private MemberService memberService;
	@Autowired
	private OrderService orderService;
	@Autowired
	private UorderService uorderService;
	@Autowired
	private UorderPayService uorderPayService;
	@Autowired
	private SplitService splitService;
	@Autowired
	private PayService payService;
	@Autowired
	private ConfigService configService;
	@Autowired
	private PushService pushService;
	@Autowired
	private PushInterService pushInterService;
	@Autowired
	private MessageService messageService;
	
    /**
     *  订单支付(余额或者购物专用金) 
     * @param token
     * @param member_id
     * @param request
     * @param response
     * @param memberVO
     * @param pay_type
     * @param order_pay_no
     * @param pay_pwd
     * @return
     * @throws IOException
     */
    @ResponseBody
 	@RequestMapping(value="/payOrderByBalanceCash",method=RequestMethod.POST)
 	public Object payOrderByBalanceCash(@RequestHeader(value = "LANG", required = false) String lang,@RequestHeader (value="AUTHORIZATION", required=false) String token,
 			@RequestHeader (value="SECRET", required=false)  String member_id,HttpServletRequest request, HttpServletResponse response
 			,MemberVO memberVO, String pay_type,String order_pay_no,String pay_pwd) throws Exception{
 		String country=null;
 		if(lang==null){
 			country = "1";
 		}else{
 			country = "0";
 		}
 		Map<String, Object> map = new HashMap<String, Object>();
 		if(pay_type==null||order_pay_no==null){
 			return PackageUtil.packageParams(10001,"缺少必选参数","","");
 		}
 		/*if(!"3".equals(pay_type)&&!"4".equals(pay_type)){
 			return PackageUtil.packageParams(10000,"参数不正确","","");
 		}*/
 		if(!"3".equals(pay_type)){
 			return PackageUtil.packageParams(10000,"参数不正确","","");
 		}
 		
 		String[] order_id_List = order_pay_no.split(",");
 		List<String> order_id_array =  orderService.getRealPayOrderId(order_id_List);
 		if(order_id_array!=null&&order_id_array.size()>0){
 			order_id_List = new String[order_id_array.size()];
 			for (int i = 0; i < order_id_array.size(); i++) {
 				order_id_List[i]= order_id_array.get(i);
 			}
 		}else{
 			return PackageUtil.packageParams(10906,"订单状态异常","","");
 		}
 		memberVO = memberService.getAllInfoById(member_id);
 		if(!memberVO.getPay_pwd().equals(pay_pwd)){
 			return PackageUtil.packageParams(12005,"支付密码错误","","");
 		}
 		
 		//支付价格
 		String total_price= orderService.getTotalPriceByPayNo(order_id_List,memberVO.getId());
 		//余额购买
 		if("3".equals(pay_type)){
 			if("0".equals(country)){
 				if(Double.parseDouble(total_price)>Double.parseDouble(memberVO.getFree_cash_en())){
 	 				return PackageUtil.packageParams(10907,"余额不足","","");
 	 			}
 			}else{
 				if(Double.parseDouble(total_price)>Double.parseDouble(memberVO.getFree_cash())){
 	 				return PackageUtil.packageParams(10907,"余额不足","","");
 	 			}
 			}
 			
 		}
 		/*//购物专用金购买
 		else{
 			if(Double.parseDouble(total_price)>Double.parseDouble(memberVO.getGood_cash())){
				return PackageUtil.packageParams(10914,"购物专用金不足","","");
			}
 		}*/
 		
 		boolean state = uorderPayService.dealPayOrderBalaceCash(order_id_List,pay_type,memberVO,total_price);
 		if(state){
 			//分润
 			if("3".equals(pay_type)){
 				benifitAfterOrderPay(order_id_List,memberVO);
 			}
 			//
 			List<OrderVO> orderList = orderService.getSimpleOrderByIdList(order_id_List);
 			if("1".equals(country)){
 				pushService.pushOrderPay(orderList);
 			}else{
 				pushInterService.pushOrderPay(orderList,country);
 			}
 		}
	 		OrderVO order =orderService.getOrderAddressByPayNo(order_id_List);
	 		map.put("adress_tel", order.getAddress_tel());
			map.put("adress_name", order.getAddress_name());
			map.put("adress_content", order.getAddress_content());
			map.put("address_tel", order.getAddress_tel());
			map.put("address_name", order.getAddress_name());
			map.put("address_content", order.getAddress_content());
			map.put("amount", total_price);
			map.put("ticket", order.getTotal_ticket());
			map.put("state", "1");
			
 		return PackageUtil.packageParams(200,"successs",map,"");
 	}
    
    /**
     * 支付订单以后 分润
     * @throws Exception 
     */
    public void benifitAfterOrderPay(String[] order_id_List,MemberVO memberVO) throws Exception{
    	List<OrderVO> orderList = orderService.getSimpleOrderByIdList(order_id_List);
		if(orderList!=null&&orderList.size()>0){
			for (int i = 0; i < orderList.size(); i++) {
				OrderVO oneOrder = orderList.get(i);
				String total_ticket = "";
				String country = orderList.get(i).getCountry();
				total_ticket = orderService.getToTalStandardTicket(oneOrder.getId());
				if(!"4".equals(oneOrder.getPay_type())){
					//没有使用兑换券
					if("0".equals(oneOrder.getTicket_status())){
						splitService.split(memberVO.getId(), memberVO.getLevel(), 2, total_ticket, oneOrder.getMember_rate(), oneOrder.getId(), oneOrder.getJoin_cash(), null,null);
						if(Integer.parseInt(total_ticket)==0&&Double.parseDouble(oneOrder.getJoin_cash())>0){	
							splitService.splitJoinAward(memberVO.getId(), memberVO.getLevel(), 2, total_ticket, oneOrder.getMember_rate() , oneOrder.getId(), oneOrder.getJoin_cash(), null);
						}
					}
					//使用了兑换券
					else{
						if(Double.parseDouble(oneOrder.getJoin_cash())>0){	
								splitService.splitJoinAward(memberVO.getId(), memberVO.getLevel(), 2, total_ticket, oneOrder.getMember_rate() , oneOrder.getId(), oneOrder.getJoin_cash(), null);
						}
					}
					//oneOrder.getId() 只买东西时分润推送
					if("1".equals(country)){
						pushService.BuyGoodsProfit(oneOrder.getId());
			        }else{
			            pushInterService.BuyGoodsProfit(oneOrder.getId(),country);
			        }
				}
				
			}
		}
    }

    /**
     *  退包裹 (余额)
     *  refund_type 0全退 1不分退
     *  cancel_state 1 卖家取消包裹
     */
    @ResponseBody
	@RequestMapping(value="/refundBalance",method=RequestMethod.POST)
	public Object refundBalance(@RequestHeader (value="AUTHORIZATION", required=false) String token,
			@RequestHeader (value="SECRET", required=false)  String member_id,HttpServletRequest request, HttpServletResponse response
			,MemberVO memberVO,String order_id,String refund_type,String total_price,String total_ticket,String cancel_state) throws Exception{
		
			OrderVO order = orderService.getOrderById(order_id);
			
			System.out.println("余额退款");
			System.out.println(refund_type);
			System.out.println(order_id);
			System.out.println("要退的卷+++++++++++++++++++++++++++++++++"+total_ticket);
			System.out.println(cancel_state);
			//没有使用 购物券
			if("0".equals(order.getTicket_status())){
				//部分退 没花卷
				if("1".equals(refund_type)){
					//购物专用金
					if("4".equals(order.getPay_type())){
						splitService.payBack(order_id, "4", order.getCreate_by(), null, total_price);
					}
					//余额购买
					else if("3".equals(order.getPay_type())){
						splitService.payBack(order_id, "3", order.getCreate_by(), total_price, null);
					}
				}
				//全退 没花卷
				else if("0".equals(refund_type)){
					//购物专用金
					if("4".equals(order.getPay_type())){
						splitService.payBack(order_id, "4", order.getCreate_by(), null, total_price);
					}
					//余额购买
					else if("3".equals(order.getPay_type())){
						splitService.payBack(order_id, "3", order.getCreate_by(), total_price, null);
					}
					//商家取消订单时推送
					if("1".equals(cancel_state)){
						sendCancelOrderPush(order.getCreate_by(),order.getNo());
					}
				}
				
				// 交易退款 price 购买钱数 buy_cash 购物专用金 二选一 pay_type(兑换券,订单表的pay_type)
				
			}
			
			//使用 购物券
			else if("1".equals(order.getTicket_status())){
				//部分退款
				if("1".equals(refund_type)){
					//String member_id, int num, String order_id,String pay_type, String price, String buy_cash
					//余额 购买时
					if(order.getPay_type().equals("3")){
						splitService.deleteTicketBuyAndGenBackLog(order.getCreate_by(), Integer.parseInt(total_ticket), order_id,"3",total_price,null);
					}
					//购物专用金购买时
					else if(order.getPay_type().equals("4")){
						splitService.deleteTicketBuyAndGenBackLog(order.getCreate_by(), Integer.parseInt(total_ticket), order_id,"4",null,total_price);	
					}
				}
				//全退
				else{				
					//余额 购买时
					if(order.getPay_type().equals("3")){
						splitService.payBackUseTicket(order_id,"3",order.getCreate_by(),total_price,null);
					}
					//购物专用金购买时
					else if(order.getPay_type().equals("4")){
						splitService.payBackUseTicket(order_id,order.getPay_type(),order.getCreate_by(),null,total_price);	
					}
					//商家取消订单时推送
					if("1".equals(cancel_state)){
						sendCancelOrderPush(order.getCreate_by(),order.getNo());
					}
				}
			}
			
			//余额退款 推送 total_price
			if("1".equals(order.getTicket_status())&&"0".equals(order.getTotal_price())){
				
			}else{
				if("1".equals(order.getCountry())){
					pushService.pushRefund(total_price,order.getCreate_by(),order.getPay_type());
				}else{
					pushInterService.pushRefund(total_price,order.getCreate_by(),order.getPay_type(),order.getCountry());
				}
				
			}
			
			return PackageUtil.packageParams(200,"successs","","");
	}
	
	/**
	 * 退支付宝支付订单 
	 */
	@ResponseBody
	@RequestMapping(value="/orderRefundAlipay",method=RequestMethod.POST)
	public Object orderRefundAlipay(@RequestHeader (value="AUTHORIZATION", required=false) String token,
			@RequestHeader (value="SECRET", required=false)  String member_id,HttpServletRequest request, HttpServletResponse response
			,String out_refund_no, String out_trade_no, String total_fee,
			String refund_fee,String refund_type,String order_id,String total_ticket,String cancel_state) throws Exception{
		
		OrderVO order = orderService.getOrderById(order_id);
		if(order==null){
			return PackageUtil.packageParams(10917,"退款异常","","");
		}
		boolean  success = false;
		String reouttradeno = "";
		if(Double.parseDouble(refund_fee)==0){
			success = true;
		}else{
			//退款
			AlipayTradeRefundResponse re = payService.alipayRefund(out_trade_no, out_refund_no, total_fee, refund_fee);	
			success = re.isSuccess();
			reouttradeno = re.getOutTradeNo();
		}
		// 退款金额0  或者 退款金额 高于0
		if((success&&Double.parseDouble(refund_fee)==0)||(success&&out_trade_no.equals(reouttradeno))){
				
			//沒有使用兑换券
			if("0".equals(order.getTicket_status())){
				//全部退款
				if("0".equals(refund_type)){
					splitService.payBack(order_id, "1", order.getCreate_by(), String.valueOf(Double.parseDouble(order.getTotal_price())+Double.parseDouble(order.getFreight())), null);
						
					//商家取消订单时推送
					if("1".equals(cancel_state)){
						sendCancelOrderPush(order.getCreate_by(),order.getNo());
					}
				}
					//部分退款
				else if("1".equals(refund_type)){
					splitService.payBack(order_id, "1", order.getCreate_by(), refund_fee, null);
				}	
			}
				
			//使用兑换券
			else if("1".equals(order.getTicket_status())){
				//部分退款
				if("1".equals(refund_type)){
					splitService.deleteTicketBuyAndGenBackLog(order.getCreate_by(), Integer.parseInt(total_ticket), order_id,"1",refund_fee,null);
				} 
				//全部退款
				else if("0".equals(refund_type)){
					splitService.payBackUseTicket(order_id,"1",order.getCreate_by(),String.valueOf(Double.parseDouble(order.getTotal_price())+Double.parseDouble(order.getFreight())),null);		
					//商家取消订单时推送
					if("1".equals(cancel_state)){
						sendCancelOrderPush(order.getCreate_by(),order.getNo());
					}	
				}
			}
			
			//支付宝退款 refund_fee
			//pushService.pushRefund(refund_fee,order.getCreate_by(),"");
			return PackageUtil.packageParams(200,"successs","","");
		}else{
			return PackageUtil.packageParams(10917,"退款异常","","");
		}
	}
	
	/**
	 *退微信支付订单 
	 */
	@ResponseBody
	@RequestMapping(value="/orderRefundWechat",method=RequestMethod.POST)
	public Object orderRefundWechat(@RequestHeader (value="AUTHORIZATION", required=false) String token,
			@RequestHeader (value="SECRET", required=false)  String member_id,HttpServletRequest request, HttpServletResponse response
			,String out_refund_no, String out_trade_no, String refund_fee,
			String total_fee,String refund_type,String order_id,String total_ticket,String cancel_state) throws Exception{
		
		OrderVO order = orderService.getOrderById(order_id);
		OrderPayVO payVO =  payService.getPayOrderByNo(out_trade_no);
		if(order==null||payVO==null){
			return PackageUtil.packageParams(10917,"退款异常","","");
		}
		
		JSONObject obj = JSON.parseObject(payVO.getParams());
		String trade_type = "APP";
		if(obj.get("trade_type")!=null){
			if("JSAPI".equals(obj.get("trade_type").toString())){
				trade_type = "JSAPI";
			}
		}
		System.out.println("**********************************"+refund_fee);
		System.out.println("**********************************"+total_fee);
		System.out.println("**********************************"+total_ticket);
		String result = "";
		Map<String, String> map = new HashMap<String,String>();
		if(Double.parseDouble(refund_fee)!=0){
			result = payService.wechatRefund(request,out_trade_no, out_refund_no, total_fee, refund_fee,trade_type);
			map = XMLUtil.doXMLParse(result);	
		}
		
		if(Double.parseDouble(refund_fee)==0||map.get("return_code").equals("SUCCESS")&&out_refund_no.equals(map.get("out_refund_no"))&&out_trade_no.equals(map.get("out_trade_no"))&&total_fee.equals(map.get("total_fee"))&&refund_fee.equals(map.get("refund_fee"))){
			
			//没有使用兑换券
			if("0".equals(order.getTicket_status())){
				
				//部分退款
				if("1".equals(refund_type)){
					splitService.payBack(order_id, "2", order.getCreate_by(), String.valueOf(Double.parseDouble(refund_fee)/100==0?"0":Double.parseDouble(refund_fee)/100), null);
				} 
				//全部退款
				else if("0".equals(refund_type)){
					splitService.payBack(order_id, "2", order.getCreate_by(), String.valueOf(Double.parseDouble(order.getTotal_price())+Double.parseDouble(order.getFreight())), null);
					//商家取消订单时推送
					if("1".equals(cancel_state)){
						sendCancelOrderPush(order.getCreate_by(),order.getNo());
					}
				}
			}
			
			//使用兑换券
			else if("1".equals(order.getTicket_status())){
				
				//部分退款
				if("1".equals(refund_type)){
					splitService.deleteTicketBuyAndGenBackLog(order.getCreate_by(), Integer.parseInt(total_ticket), order_id,"2",String.valueOf(Double.parseDouble(refund_fee)/100==0?"0":Double.parseDouble(refund_fee)/100),null);
				} 
				//全部退款
				else if("0".equals(refund_type)){
					splitService.payBackUseTicket(order_id,"2",order.getCreate_by(),String.valueOf(Double.parseDouble(order.getTotal_price())+Double.parseDouble(order.getFreight())),null);
					//商家取消订单时推送
					if("1".equals(cancel_state)){
						//sendCancelOrderPush(order.getCreate_by(),order.getNo());
					}
				}
			}
			
			//微信支付退款 refund_fee order.getCreate_by()
			//pushService.pushRefund(refund_fee,order.getCreate_by(),"");
			return PackageUtil.packageParams(200,"successs",map,"");
		}else{
			return PackageUtil.packageParams(10917,"退款异常","","");
		}
	}
	
	@ResponseBody
	@RequestMapping(value="/orderRefundPayPal",method=RequestMethod.POST)
	public Object orderRefundPayPal(@RequestHeader (value="AUTHORIZATION", required=false) String token,
			@RequestHeader (value="SECRET", required=false)  String member_id,HttpServletRequest request, HttpServletResponse response
			,String out_refund_no, String out_trade_no, String refund_fee,
			String total_fee,String refund_type,String order_id,String total_ticket,String cancel_state) throws Exception{
		
		OrderVO order = orderService.getOrderById(order_id);
		OrderPayVO payVO =  payService.getPayOrderByNo(out_trade_no);
		if(order==null||payVO==null){
			return PackageUtil.packageParams(10917,"退款异常","","");
		}
		//没有使用兑换券
		if("0".equals(order.getTicket_status())){
			
			//部分退款
			if("1".equals(refund_type)){
				splitService.payBack(order_id, "5", order.getCreate_by(), String.valueOf(Double.parseDouble(refund_fee)/100==0?"0":Double.parseDouble(refund_fee)/100), null);
			} 
			//全部退款
			else if("0".equals(refund_type)){
				splitService.payBack(order_id, "5", order.getCreate_by(), String.valueOf(Double.parseDouble(order.getTotal_price())+Double.parseDouble(order.getFreight())), null);
				//商家取消订单时推送
				if("1".equals(cancel_state)){
					sendCancelOrderPush(order.getCreate_by(),order.getNo());
				}
			}
		}
		
		//使用兑换券
		else if("1".equals(order.getTicket_status())){
			
			//部分退款
			if("1".equals(refund_type)){
				splitService.deleteTicketBuyAndGenBackLog(order.getCreate_by(), Integer.parseInt(total_ticket), order_id,"5",String.valueOf(Double.parseDouble(refund_fee)/100==0?"0":Double.parseDouble(refund_fee)/100),null);
			} 
			//全部退款
			else if("0".equals(refund_type)){
				splitService.payBackUseTicket(order_id,"5",order.getCreate_by(),String.valueOf(Double.parseDouble(order.getTotal_price())+Double.parseDouble(order.getFreight())),null);
				//商家取消订单时推送
				if("1".equals(cancel_state)){
					//sendCancelOrderPush(order.getCreate_by(),order.getNo());
				}
			}
		}
		return PackageUtil.packageParams(200,"successs","","");
		
	}
	
	@ResponseBody
	@RequestMapping(value="/orderRefundPayssion",method=RequestMethod.POST)
	public Object orderRefundPayssion(@RequestHeader (value="AUTHORIZATION", required=false) String token,
			@RequestHeader (value="SECRET", required=false)  String member_id,HttpServletRequest request, HttpServletResponse response
			,String out_refund_no, String out_trade_no, String refund_fee,
			String total_fee,String refund_type,String order_id,String total_ticket,String cancel_state) throws Exception{
		
		OrderVO order = orderService.getOrderById(order_id);
		OrderPayVO payVO =  payService.getPayOrderByNo(out_trade_no);
		if(order==null||payVO==null){
			return PackageUtil.packageParams(10917,"退款异常","","");
		}
		//没有使用兑换券
		if("0".equals(order.getTicket_status())){
			
			//部分退款
			if("1".equals(refund_type)){
				splitService.payBack(order_id, "6", order.getCreate_by(), String.valueOf(Double.parseDouble(refund_fee)/100==0?"0":Double.parseDouble(refund_fee)/100), null);
			} 
			//全部退款
			else if("0".equals(refund_type)){
				splitService.payBack(order_id, "6", order.getCreate_by(), String.valueOf(Double.parseDouble(order.getTotal_price())+Double.parseDouble(order.getFreight())), null);
				//商家取消订单时推送
				if("1".equals(cancel_state)){
					sendCancelOrderPush(order.getCreate_by(),order.getNo());
				}
			}
		}
		
		//使用兑换券
		else if("1".equals(order.getTicket_status())){
			
			//部分退款
			if("1".equals(refund_type)){
				splitService.deleteTicketBuyAndGenBackLog(order.getCreate_by(), Integer.parseInt(total_ticket), order_id,"6",String.valueOf(Double.parseDouble(refund_fee)/100==0?"0":Double.parseDouble(refund_fee)/100),null);
			} 
			//全部退款
			else if("0".equals(refund_type)){
				splitService.payBackUseTicket(order_id,"6",order.getCreate_by(),String.valueOf(Double.parseDouble(order.getTotal_price())+Double.parseDouble(order.getFreight())),null);
				//商家取消订单时推送
				if("1".equals(cancel_state)){
					//sendCancelOrderPush(order.getCreate_by(),order.getNo());
				}
			}
		}
		return PackageUtil.packageParams(200,"successs","","");
		
	}
	
	
	/**
	 *  取消包裹推送
	 * @param member_id
	 * @param order_no
	 */
	public void sendCancelOrderPush(String member_id,String order_no){
		/*
		 	notice_num    1
			sys_num         2
			ems_num       3
			cash_num      4
			praise_num    5
		*/
		System.out.println("推送********************");
		messageService.updMemberMsg(member_id,"2");
		pushService.sendCancelOrderPush(member_id,order_no);
	}
	
}
